package org.wk.user.service;

import cn.jiguang.common.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.wk.core.common.tool.RegexUtils;
import org.wk.core.common.view.PageVo;
import org.wk.core.common.view.ResponseVo;
import org.wk.core.db.tool.WebUtils;
import org.wk.user.dao.UserDao;
import org.wk.user.dao.UserSuggestionsDao;
import org.wk.user.domain.User;
import org.wk.user.domain.UserSuggestions;
import org.wk.user.enums.FeedbackStatus;
import org.wk.user.enums.ResponseCode;
import org.wk.user.view.UserSuggestionsVo;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author TangShenShen
 * @Description: 意见反馈服务实现类
 * @date 2018/5/2916:48
 */
@Service
public class UserSuggestionsServiceImpl implements UserSuggestionsService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserSuggestionsDao userSuggestionsDao;
    @Autowired
    private UserDao userDao;

    /**
     * 保存用户的意见反馈
     * @author TangShenShen
     * @date 2018/5/29 17:08
     */
    @Override
    public ResponseVo saveUserSuggestions(JSONObject jsonObject) {
        String suggestion = jsonObject.getString("suggestion");// 建议
        String mobile_number = jsonObject.getString("mobile_number");
        String suggestion_img = jsonObject.getString("suggestion_img");
        if (!RegexUtils.checkMobileNum(mobile_number)){
            return new ResponseVo(ResponseCode.MOBILE_NUMBER_ERROR);
        }
        UserSuggestions userSuggestions = new UserSuggestions();
        userSuggestions.setUserId(WebUtils.getUser().getId());
        Optional<User> user = userDao.findById(WebUtils.getUser().getId());
        if (user.isPresent()){
            userSuggestions.setNickName(user.get().getNickName());
        }
        //userSuggestions.setNickName((String) WebUtils.getUser().getData().get("nickName"));
        userSuggestions.setFeedbackStatusCode(FeedbackStatus.UNPROCESSED.getCode());
        userSuggestions.setFeedbackStatusName(FeedbackStatus.UNPROCESSED.getName());
        userSuggestions.setSuggestion(suggestion);
        userSuggestions.setSuggestionImg(suggestion_img);
        userSuggestions.setMobileNumber(mobile_number);
        userSuggestions.setDelFlag("N");
        userSuggestionsDao.save(userSuggestions);
        return ResponseVo.success();
    }

    @Override
    public PageVo queryPage(Map<String, Object> params) {
        String delFlag = (String) params.get("delFlag");
        String nickName = (String) params.get("nickName");
        String statusCode = (String) params.get("statusCode");
        String temp = (String)params.get("page");
        Integer pageNo = temp==null?0:Integer.parseInt(temp)-1;
        temp = (String) params.get("limit");
        Integer pageSize = temp==null?10:Integer.parseInt(temp);

        UserSuggestions usuggestions = new UserSuggestions();
        usuggestions.setDelFlag("N");  // 未删除的
        usuggestions.setNickName(nickName);
        Page<UserSuggestions> page = userSuggestionsDao.findAll(new Specification<UserSuggestions>() {
            @Override
            public Predicate toPredicate(Root<UserSuggestions> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> list = new ArrayList<Predicate>();
                if(null!=usuggestions.getNickName()&&!"".equals(usuggestions.getNickName())){
                    list.add(criteriaBuilder.like(root.get("nickName").as(String.class), "%"+usuggestions.getNickName()+"%"));
                }
                list.add(criteriaBuilder.equal(root.get("delFlag").as(String.class), usuggestions.getDelFlag()));
                Predicate[] p = new Predicate[list.size()];
                return criteriaBuilder.and(list.toArray(p));
            }
        }, PageRequest.of(pageNo, pageSize, new Sort(Sort.Direction.DESC, "createTime")));

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<UserSuggestionsVo> list = new ArrayList<>();
        for(UserSuggestions userSuggestions : page.getContent()){
            UserSuggestionsVo userSuggestionsVo = new UserSuggestionsVo();
            BeanUtils.copyProperties(userSuggestions, userSuggestionsVo);
            userSuggestionsVo.setCreateTime(sdf.format(userSuggestions.getCreateTime()));
            list.add(userSuggestionsVo);
        }
        PageVo<UserSuggestionsVo> pageVo = new PageVo<UserSuggestionsVo>();
        pageVo.setTotal(page.getTotalElements());
        pageVo.setPageNo(++pageNo);
        pageVo.setPageSize(pageSize);
        pageVo.setResult(list);
        pageVo.setTotalPages(page.getTotalPages());
        return pageVo;
    }

    @Transactional
    @Override
    public void deleteBatch(String[] sugIds) {
        String delFlag = "Y";
        userSuggestionsDao.updateDelFlagByIds(delFlag, Arrays.asList(sugIds));
    }

    @Override
    public UserSuggestionsVo selectById(String id) {
        Optional<UserSuggestions> optional = userSuggestionsDao.findById(id);
        UserSuggestions suggestions = optional.get();
        UserSuggestionsVo suggestionsVo = new UserSuggestionsVo();
        BeanUtils.copyProperties(suggestions, suggestionsVo);
        suggestionsVo.setId(suggestions.getId());
        return suggestionsVo;
    }

    /*
     * @description 处理建议
     * @param
     * @author ZhaoPing'an
     * @date 2018/7/16 14:41
     */
    @Override
    public void updateProcessed(String id) {
        UserSuggestionsVo userSuggestionsVo = new UserSuggestionsVo();

        UserSuggestions entity = userSuggestionsDao.getOne(id);
        entity.setFeedbackStatusCode(FeedbackStatus.PROCESSED.getCode());
        entity.setFeedbackStatusName(FeedbackStatus.PROCESSED.getName());
        userSuggestionsDao.saveOrUpdate(entity);
    }
}
